package com.binvshe.binvshe.contacts;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.app.storagemanager.SpDao;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.pachong.android.baseuicomponent.CompState;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.baseuicomponent.fragment.SwipeListFragment;
import com.pachong.android.frameworkbase.dialog.AlertDialogFragment;
import com.pachong.android.frameworkbase.utils.GsonUtils;
import com.pachong.android.frameworkbase.utils.SLog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


/**
 * 添加好友界面
 * 获取手机联系人，并且判断是否可加好友
 * <p>
 * 默认存在通讯录
 *
 * @Author: PV
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 11-01
 * @Version: 1.0.0
 */
public class FriendContactsFragment extends SwipeListFragment {
    List<ContactsService.Contact> contacts = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        setPullToRefreshEnable(false);
        setAutoLoading(false);

        String contactsStr = SpDao.getCacheContacts(getActivity());
        if (!TextUtils.isEmpty(contactsStr)) {
            contacts = GsonUtils.string2ObjecetList(contactsStr, ContactsService.Contact[].class);
            if (contacts == null || contacts.size() == 0) {
                setState(CompState.EMPTY);
            }
        } else {
            setState(CompState.EMPTY);
        }

      /*  contacts = new ArrayList();
        ContactsService.Contact contact1 = new ContactsService.Contact("18959232125", "xinhiuang");
        ContactsService.Contact contact2 = new ContactsService.Contact("15960279629", "chenglei");
        contacts.add(contact1);
        contacts.add(contact2);

        FriendContactAdapter adapter = (FriendContactAdapter)getAdapter();
        adapter.setPhoneContacts(contacts);
        startLoading();*/

        if (getState() != CompState.EMPTY) {
            startLoading();
        } else {
            final AlertDialogFragment dialogFragment = new AlertDialogFragment();
            String prompt = "“" + getString(R.string.app_name) + "”";
            dialogFragment.setMessage(prompt+"无法访问您的通讯录\n请开启通讯录访问授权")
                    .setTitle("提示").setPositiveButton("好的", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialogFragment.dismiss();
                }
            }).show(getChildFragmentManager());
        }

        return view;
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new FriendContactAdapter(getActivity());
    }


    @Override
    public void onStartLoading() {
        SLog.e("vivi", "onStartLoading");
        MyHttpRequest request = new MyHttpRequest(getContext());
        JSONArray contactsArray = combinContactJsonObj();

        try {
            JSONObject jobj = new JSONObject();
            jobj.put("items", contactsArray);
            request.post(UrlCenter.PHONE_CONTACTS, jobj, new DataRequestListener<List<FriendContactAdapter.ContactBean>>(FriendContactAdapter.ContactBean.class) {

                @Override
                public void onSuccess(List<FriendContactAdapter.ContactBean> list) {
                    super.onSuccess(list);
                    SLog.e("vivi", "onSuccess");
                    if (list != null) {
                        setState(CompState.DATA);
                        getAdapter().getData().addAll(list);
                        getAdapter().notifyDataSetChanged();
                        ((FriendContactAdapter) getAdapter()).setPhoneContacts(contacts);
                    }else {
                        setState(CompState.EMPTY);
                    }
                }

                @Override
                public void onStart(Context context, String url) {
                    enableProgress(false);
                    super.onStart(context, url);
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    SLog.e("vivi", strMsg);
                    setState(CompState.EMPTY_ERROR);
                }

            });
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private JSONArray combinContactJsonObj() {
        JSONArray jsonArray = new JSONArray();
        JSONObject tmpObj = null;
        for (ContactsService.Contact contact : contacts) {
            try {
                tmpObj = new JSONObject();
                tmpObj.put("name", contact.name);
                tmpObj.put("phone", contact.phoneNum);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(tmpObj);
            tmpObj = null;
        }

        return jsonArray;
    }


    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long itemId) {
//        People people = (People) getData().get(position);
//        ChatHelper.startSingleChat(getActivity(), people.getPhone(), people.getNick_name(), people.getPortrait());
    }

}
